package com.mxprojects.gui
{
	import com.mxprojects.constructors.SimpleTextField;
	import com.mxprojects.io.BoardCookie;
	import com.mxprojects.io.Config;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.DeepLinking;
	import com.mxprojects.io.ServerHandler;
	import com.mxprojects.io.UserControl;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	import com.mxprojects.views.Admin;
	import com.mxprojects.views.LoginDialog;
	import com.mxprojects.views.PrivateMessages;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.TextEvent;
	import flash.events.TimerEvent;
	import flash.text.TextFieldAutoSize;
	import flash.utils.Timer;
	
	public class Header extends MovieClip
	{
		private const LINK_SPACE:String = "&nbsp;&nbsp;&nbsp;";
		private const CHECK_MESSAGES:String = "checkMessages";

		
		public var background:MovieClip;
		
		private var currentUser:SimpleTextField;
		private var currentUserAlign:String;
		private var quickSearch:QuickSearch;
		private var checkingMessages:Boolean;
		private var checkingTimer:Timer;
		
		public function Header(){}
		
		public function init():void {
			background.width = MXP3.wStage;
		}
		
		public function setupCSS():void {
			//based on the height, set where the board should go
			Styles.setProperties(background, ".headerBackground");
			Styles.setProperties(MXP3.footer.background, ".footerBackground");
			MXP3.contentHolder.y = background.height;
			
			//setup the current user text block
			currentUser = new SimpleTextField("");
			currentUser.x = Styles.css.getStyle(".headerUserOptions").x;
			currentUser.y = Styles.css.getStyle(".headerUserOptions").y;
			addChild(currentUser);
			
			//depending on the alignment do different things to the text field
			currentUserAlign = Styles.css.getStyle(".headerUserOptions").textAlign;
			if(currentUserAlign == "right"){
				currentUser.autoSize = TextFieldAutoSize.RIGHT;
				currentUser.x = Math.round(MXP3.wStage - currentUser.width);
			}else if(currentUserAlign == "center"){
				currentUser.autoSize = TextFieldAutoSize.CENTER;
				currentUser.x = Math.round(MXP3.wStage/2 - currentUser.width/2);
			}
			
			//setup the quick search
			quickSearch = new QuickSearch();
			addChild(quickSearch);
			
			//setup breadcrumbs
			BreadCrumbs.setup();
			
			//setup the page navigation
			PageNav.setup();
			
			//setup the auto pm checker
			setupAutoPrivate();
		}
		
		public function resize():void {
			background.width = MXP3.wStage;
			if(quickSearch != null){
				PageNav.resize();
				
				//see if there was a bg image
				var bgImage:DisplayObject = getChildByName("backgroundImage");
				if(bgImage != null){
					bgImage.width = MXP3.wStage;
				}
				
				//depending on what the current user alignment is set to, we might need to do stuff
				if(currentUserAlign == "right"){
					currentUser.x = Math.round(MXP3.wStage - currentUser.width);
				}else if(currentUserAlign == "center"){
					currentUser.x = Math.round(MXP3.wStage/2 - currentUser.width/2);
				}
				
				//move the quick search
				quickSearch.resize();
			}
		}
		
		
		public function showDefaultUserInfo():void {			
			//if they are not logged in show the message to register or login
			currentUser.htmlText = 	"<span class=\"headerUserOptions\"><span class=\"headerUserText\">"+ Language.main(Word.MESSAGE_NOT_LOGGED_IN) + "</span>" + LINK_SPACE +
									"<a href=\"event:"+Word.SEARCH+"\">" +Language.main(Word.ADVANCED_SEARCH)+ "</a>" + LINK_SPACE +
									"<a href=\"event:"+Word.REGISTER+"\">"+Language.main(Word.REGISTER) +"</a>" + LINK_SPACE +
									"<a class=\"headerLogin\" href=\"event:"+Word.LOGIN+"\">"+ Language.main(Word.LOGIN) +"</a></span>";
						
			//listen for clicks
			currentUser.addEventListener(TextEvent.LINK, parseLink);
			
			//since they are no longer logged in, stop looking for private messages
			if(checkingTimer.running){
				checkingTimer.stop();
			}
		}
		
		
		public function showLoggedInUser(username:String, totalMessages:int, newMessages:int = 0, isAdmin:int = 0):void {			
			var userText:String = "<span class=\"headerUserOptions\"><span class=\"headerUserText\">" +  Language.main(Word.WELCOME) + " " + username + "</span>" + LINK_SPACE;
						
			//setup a var for plurrel
			var messageOrMessages:String = Language.main(Word.MESSAGES);							
			
			//check new messages
			if(newMessages > 0){
				
				//check for plurrel
				if(newMessages == 1){
					messageOrMessages = Language.main(Word.MESSAGE);
				}
				
				//build the private message text if logged in
				userText += "<a href=\"event:"+Word.PRIVATE_MESSAGES+"\"><span class=\"headerPrivateMessages\">("+newMessages+")</span> "+ Language.main(Word.NEW) +" "+Language.main(Word.PRIVATE)+" "+messageOrMessages+"</a>";
			}else{
				//just list the amount of messages
				//check for plurrel
				if(totalMessages == 1){
					//messageOrMessages = Language.main(Word.MESSAGE);
				}
				
				//build the regular messages
				//userText += "<a href=\"event:"+Word.PRIVATE_MESSAGES+"\"><span class=\"headerPrivateMessages\">("+totalMessages+")</span> "+Language.main(Word.PRIVATE)+" "+messageOrMessages+"</a>";
				userText += "<a href=\"event:"+Word.PRIVATE_MESSAGES+"\"><span class=\"headerPrivateMessages\"></span>"+Language.main(Word.PRIVATE)+" "+messageOrMessages+"</a>";
			}
			
			//mange the profile
			userText +=	LINK_SPACE + "<a href=\"event:"+Word.PROFILE+"\">"+ Language.main(Word.PROFILE) +"</a>" + LINK_SPACE;
			
			//check if they are an admin
			if(isAdmin == 1){
				userText +=	"<a href=\"event:"+Word.ADMIN+"\">"+ Language.main(Word.ADMIN) +"</a>" + LINK_SPACE;
			}
			
			//logout
			userText += "<a href=\"event:"+Word.SEARCH+"\">"+Language.main(Word.ADVANCED_SEARCH) +"</a>" + LINK_SPACE +
						"<a href=\"event:"+Word.LOGOUT+"\">"+ Language.main(Word.LOGOUT) +"</a></span>";
			
			//put the string in the box
			currentUser.htmlText = userText;
			
			//listen for clicks
			currentUser.addEventListener(TextEvent.LINK, parseLink);
		}
		
		public function refreshHeader(event:TimerEvent = null):void {
			//make sure they are logged in
			if(!UserControl.loggedIn){
				return;
			}
			
			//if this isn't coming from a timer event then we need to make sure the timer is still running
			if(event == null){
				//reset and start the timer if it's not running
				if(!checkingTimer.running){
					//reset and reload
					checkingTimer.reset();
					checkingTimer.start();
				}
			}
			
			//only check the messages if we aren't already checking them
			if(!checkingMessages){
				trace("REFRESHING HEADER");
				//this will refresh the text in the header to make sure we've got the latest and greatest
				var dataToSend:Object = new Object();
				dataToSend.username = BoardCookie.getUser();
				dataToSend.password = BoardCookie.getPassword();
				dataToSend.privateMessageLimit = Config.PRIVATE_MESSAGE_LIMIT;
				
				//set the location
				dataToSend.location = CHECK_MESSAGES;
					
				//load the stuff
				var serverHandler:ServerHandler = new ServerHandler();
				serverHandler.transmitData("privatemessages.php", dataToSend);
				serverHandler.listenForData(processRefresh);
				
				//we are checking messages
				checkingMessages = true;
			}
		}
		
		private function processRefresh(event:CustomEvent):void {
			var data:Object = event.getServerData();
			
			//handle the data in the header
			showLoggedInUser(data.username, data.privateTotal, data.privateNew, data.admin);
			
			//we are done checking the messages
			checkingMessages = false;
		}
		
		private function setupAutoPrivate():void {
			//this will start the timer to handle the auto-checking
			checkingTimer = new Timer(Config.PRIVATE_MESSAGE_AUTO_CHECK_MINS * 1000 * 60, Config.PRIVATE_MESSAGE_AUTO_CHECK_COUNT);
			checkingTimer.addEventListener(TimerEvent.TIMER, refreshHeader, false, 0, true);
			
			//we are not checking messages
			checkingMessages = false;
		}
		
		private function parseLink(event:TextEvent):void {
			switch(event.text){
				case Word.LOGIN:
					LoginDialog.show();
				break;
				
				case Word.LOGOUT:
					UserControl.logout();
				break;
				
				case Word.PROFILE:		
				case Word.SEARCH:
				case Word.REGISTER:
				case Word.ADMIN:
					DeepLinking.setLink(event.text, DeepLinking.createLinkArray());
				break;
				
				case Word.PRIVATE_MESSAGES:
					PrivateMessages.load();
				break;
			}
		}
	}
}